﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using System.Threading;
using DocManagerORM.ORM;

namespace DocManagerAutomation
{
  
    public class BaseCusControl :ContentControl
    {
        public System.Windows.Controls.Menu MenuDescrittivo { get; set; } 
 

        string m_Azione = "";
        Action<string> m_SwitchHandler;

        
        public static string[] RuoliUtente { get; set; }
        public static string UserName { get; set; }

        public static aspnet_Membership UtenteDati { get; set; }

        public static System.Web.Security.RolePrincipal  PrincipalIdentity { get; set; }

        static BaseCusControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(BaseCusControl),
                new FrameworkPropertyMetadata(typeof(BaseCusControl)));

            settaPrincipale();

        }//fm
       

        public Frame getFrameContainer()
        {
            dynamic winMain = Application.Current.MainWindow;
            return winMain.FrameContainer;
        }//fM


        public static SettingsBaseApplicazione SettingsBaseApplicazione
        {            
         get {
             try { return QueryBase.getSettingsBaseApplicazione(); }
            catch (Exception ex)
             {
                 messaggiaStatic("Impossibile prelevare le SettingsBaseApplicazione dell'applicazione"); 
                return null; }            
           }
        }

        protected void messaggia(string pMessage)
        {
            MessageBox.Show(pMessage, "Avvisi", MessageBoxButton.OK, MessageBoxImage.Information);
        }//fM

        protected static void messaggiaStatic(string pMessage)
        {
            MessageBox.Show(pMessage, "Avvisi", MessageBoxButton.OK, MessageBoxImage.Information);
        }//fM

        protected static void settaPrincipale()
        {

            if (SettingsBaseApplicazione.ImpersonatePcUser)
            {
                UserName = Environment.UserName;
            }
            //altrimenti screeen DialogResultConverter logon

            
            var membershipUser = Membership.GetUser(UserName);

            if (membershipUser == null)
            {   messaggiaStatic(string.Format("Utente {0} non trovato ", UserName)); 
                return; 
            }
            
                
            UserName = membershipUser.UserName;

            var identity =  new GenericIdentity(UserName);
            PrincipalIdentity = new RolePrincipal(identity);
            
            if (!PrincipalIdentity.Identity.IsAuthenticated)
            {
                messaggiaStatic("Utente non autenticato !! eseguire l'autenticazione !!");
                return;
            }

            try
            {
                UtenteDati = new QueryUsers().getMEMBERSHIP(UserName).FirstOrDefault();
            }
            catch (Exception ex)
            { }

            Thread.CurrentPrincipal = PrincipalIdentity;
            RuoliUtente = Roles.GetRolesForUser();
            
        }//fM


        public bool UtenteIsInRole(string pRuolo)
        { 
           return ( Thread.CurrentPrincipal.IsInRole(pRuolo) ? true:false );
        }//fM
      

        public void addMenuHandlerToMenu(Action<string> pSwitchHandler )
        {
            m_SwitchHandler = pSwitchHandler;         
        }//fM

        public void addMenuItemsToMenu(MenuItem[] pMenuItems)
        {

            if (MenuDescrittivo == null) tryGetMenu();
            if (MenuDescrittivo == null) return;

            foreach (var item in pMenuItems)
            {
                MenuDescrittivo.Items.Add(item);   
            }
           
        }//fM

        private void tryGetMenu()
        {
            var menu = Template.FindName("menuPage", this) as Menu;

            if (menu == null)
            {
                messaggia("Menu della classe base NON trovato"); return;
            }

            MenuDescrittivo = menu;
            menu.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(menuPage_Click)); 
        
        }//fM

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            tryGetMenu();                   
        }   


        private void menuPage_Click(object sender, RoutedEventArgs e)
        {
            MenuHandler(e);
        }//fm

        private void MenuHandler(RoutedEventArgs e)
        {
            m_Azione = ((MenuItem)e.OriginalSource).Header.ToString().ToLower();
            
            switch (m_Azione)
            {
                case "exit":
                    var par = this.Parent;
                    this.Visibility = System.Windows.Visibility.Hidden;                    
                    break;               
            }

            if (m_SwitchHandler == null) return;

            m_SwitchHandler(m_Azione); //menu del controllo derivato

        }//fM

    }//fC
}
